<template>
	<view class="content">
		<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" collection="contacts">
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<view v-for="(item,index) in data" :key="index" class="contlit">
					{{item.name}}
					<view class="btn">
						<button type="default" @click="remove(item._id)">删除</button>
						<button type="default" @click="up(item)">编辑</button>
					</view>
				</view>
			</view>
		</unicloud-db>
		
		<view class="add">
			<view class="">
				<view>联系人：</view><input type="text" v-model="item.name" />
			</view>
			<view class="">
				<view>联系电话：</view><input type="text" v-model="item.phone" />
			</view>
			<view v-if="bol">
				<button type="default" @click="add">新增</button>
			</view>
			<view v-else>
				<button type="default" @click="updata">编辑提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bol:true,
				item:{
					name:"",
					phone:""
				}
			}
		},
		onLoad() {

		},
		methods: {
			remove(id){
				this.$refs.udb.remove(id)
			},
			add(){
				const db = uniCloud.database();
				db.collection('contacts').add(this.item).then(res=>{
					console.log(res)
				}) 
			},
			up(item){
				this.id = item._id;
				delete item._id;
				this.item = item;
				this.bol = false;
			},
			updata(){
				// console.log(this.item)
				const db = uniCloud.database();
				db.collection('contacts').doc(this.id).update(this.item).then(res=>{
					console.log(res)
				})
			}
		}
	}
</script>

<style lang="less">
	.content {
		display: flex;
		flex-direction: column;
	}
	.contlit{
		display: flex;
		justify-content: space-between;
		
		.btn{
			display: flex;
			justify-content:flex-end;
		}
	}
	input{
		border: 2rpx solid #007AFF;
		width: 200rpx;
	}
	button{
		width: 200rpx;
	}

</style>
